<template>
    <Form addCode="usersAdd" v-valid="['usersSearch', 'usersAdd']" @add="user = {}; dialog.show()"
        @success="queryModel.pageNo = 1; searchUser()" inline :loading="loading" :model="queryModel" :options="options"
        submit="搜索" reset="清空" add="添加">
    </Form>
    <Table v-valid="'usersSearch'" :data="data" :cols="cols" :total="total" v-model:page="queryModel" @change="change">
        <template #status="{ row }">
            {{ row.status ? '可用' : '禁用' }}
        </template>
        <template #creation_time="{ row }">
            {{ dayjs(row.creation_time).format(dateType) }}
        </template>
        <template #action="{ row }">
            <ElButton v-valid="'usersUpdate'" type="primary" @click="user = { ...row }; dialog.show()">修改</ElButton>
            <ElButton v-valid="'usersUpdatePassword'" type="success"
                @click="userPassword = { id: row.id }; passwordRef.show()">修改密码</ElButton>
            <ElButton type="warning" v-valid="'usersChangeStatus'" @click="confirmStatus(row)">更改状态</ElButton>
            <ElButton type="danger" v-valid="'usersDelete'" @click="delUser(row)">删除</ElButton>
            <ElButton v-valid="['usersAddressAdd', 'usersAddressList']"
                @click="$router.push({ name: 'userAddress', params: { id: row.id } })">用户地址</ElButton>
        </template>
    </Table>
    <DF v-valid="['usersUpdate', 'usersAdd']" :model="user" :options="addUpdateOpts" ref="dialog"
        :title="user.id ? '修改用户' : '添加用户'" @ok="confirm" />
    <DF v-valid="'usersUpdatePassword'" :model="userPassword" :labelWidth="90" :options="updatePasswordOptions"
        ref="passwordRef" title="修改密码" @ok="confirmPassword" />
</template>

<script lang="ts" setup>
import { search, IUserSearch, IUser, add, update, AddUserType, UpdateUserType, deleteUser, changeStatus, updatePassword, IUserPassword } from '@/api/users';
import { getList, IRoles } from '@/api/roles';
import { computed, ref } from 'vue';
import dayjs from 'dayjs';
import { dateType } from '@/utils/consts';
import ask from '@/components/Confirm';
import { valid } from '@/utils/common';

/**
 * 查询模型
 */
const queryModel = ref(<IUserSearch>{
    pageNo: 1,
    pageSize: 10,
    status: '',
    role_id: 0
});
/**
 * 角色列表
 */
const roles = ref<IRoles[]>([]);
/**
 * 总条数
 */
const total = ref(0);
/**
 * loading
 */
const loading = ref(false);
/**
 * 数据
 */
const data = ref<IUser[]>([]);
/**
 * dialog引用
 */
const dialog = ref();
/**
 * 密码dialog引用
 */
const passwordRef = ref();
/**
 * 用于修改的对象
 */
const user = ref(<IUser>{});
/**
 * 用户密码
 */
const userPassword = ref(<IUserPassword>{});
/**
 * 添加修改表单配置项
 */
const addUpdateOpts = computed(() => ({
    ...(user.value.id ? null : {
        username: {
            title: '用户名',
            required: true,
            max: 20,
            rules: [{ min: 2 }]
        }
    }),
    ...(user.value.id ? {} : {
        password: {
            title: '密码',
            required: true,
            type: "password",
            max: 20,
            rules: [{ min: 6 }]
        }
    }
    ),
    phone: {
        title: '手机号',
        max: 11,
        required: true,
        rules: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' }]
    },
    role_id: {
        title: '角色',
        tag: 'select',
        required: true,
        values: roles.value.map(({ id: value, name: label }) => ({ label, value })),
    },
    email: {
        title: '邮箱',
        max: 20,
        required: true,
        rules: [{ type: 'email', message: '邮箱格式错误' }]
    }
}));

/**
 * 修改密码表单配置项
 */
const updatePasswordOptions = {
    password: {
        title: '新密码',
        required: true,
        max: 20,
        type: 'password',
        rules: [{ min: 6 }]
    },
    confirmPassword: {
        title: '确认密码',
        required: true,
        type: 'password',
        max: 20,
        rules: [{ min: 6 }, {
            validator(rule: any, value: string, callback: Function) {
                if (value !== userPassword.value.password) {
                    return callback(new Error('两次输入的密码不一致'));
                }
                callback();
            }
        }]
    }
}
/**
 * 列
 */
const cols = {
    username: {
        title: '用户名'
    },
    phone: {
        title: '手机号'
    },
    email: {
        title: '邮箱'
    },
    role_name: {
        title: '角色'
    },
    status: {
        title: '状态'
    },
    creation_time: {
        title: '创建时间'
    },
    action: {
        width: 460,
        title: '操作'
    }
}
/**
 * 更改事件
 * @param model 
 */
const change = async (model: IUserSearch) => {
    console.log(model);
}
/**
 * 搜索表单配置项
 */
const options = computed(() => ({
    username: {
        title: '用户名',
        max: 20
    },
    email: {
        title: '邮箱',
        max: 20
    },
    phone: {
        title: '手机号',
        max: 11,
        rules: [{ pattern: /^\d*$/, message: '手机号只能为数字' }]
    },
    role_id: {
        title: '角色',
        tag: 'select',
        values: [{ label: '所有', value: 0 }, ...roles.value.map(({ id: value, name: label }) => ({ label, value }))]
    },
    status: {
        title: '状态',
        tag: 'select',
        values: [{ label: '所有', value: '' }, { label: '可用', value: '1' }, { label: '禁用', value: '0' }]
    }
}));

/**
 * 提交
 * @param model 
 */
const confirm = async (model: IUser) => {
    try {
        if (model.id) {
            //@ts-ignore
            delete model.role_name;
            //@ts-ignore
            delete model.status;
            //@ts-ignore
            delete model.creation_time;
            //@ts-ignore
            delete model.password;
            //@ts-ignore
            delete model.username;
        }
        await (model.id ? update : add)(model);
        dialog.value.hide();
        searchUser();
    } catch (error) {
        console.log(error);
    }
    dialog.value.stop();
}

/**
 * 提交密码
 * @param model 
 */
const confirmPassword = async (model: IUserPassword) => {
    try {
        await updatePassword(model);
        passwordRef.value.hide();
    } catch (error) { }
    passwordRef.value.stop();
}

/**
 * 提交状态
 * @param param0 
 */
const confirmStatus = async ({ id, username, status }: IUser) => {
    let res: any;
    try {
        res = await ask(`您确定要【${status == '1' ? '禁用' : '启用'}】【${username}】吗？`)
        await changeStatus(id, status == '1' ? '0' : '1');
        searchUser();
    } catch (error) { }
    res && res();
}

/**
 * 删除用户
 * @param param0 
 */
const delUser = async ({ id, username }: IUser) => {
    let res: any;
    try {
        res = await ask(`您确定要删除【${username}】吗？`);
        await deleteUser(id);
        searchUser();
    } catch (error) { }
    res && res();
}

/**
 * 搜索
 */
const searchUser = async () => {
    if (!valid('usersSearch'))
        return;
    try {
        loading.value = true;
        const { data: list, count } = await search(queryModel.value);
        data.value = list;
        total.value = count;
    } catch (error) { }
    loading.value = false;
}

/**
 * 获取角色
 */
const getRoles = async () => {
    try {
        const list = await getList();
        roles.value = list;
    } catch (error) { }
}

searchUser();
getRoles();
</script>

<style lang="scss" scoped></style>